const fs = require("fs");
let api_front_dir = "../api/controller_front";
let admin_api_dir = "../api/controller_admin";

let rootApiPath = "/admin_api";
const baseController = {
  // 普通api
  init(routerGloab) {
    rootApiPath = "/api";
    this.registerRouter(routerGloab, api_front_dir);
    return routerGloab;
  },
  init_admin(routerGloab) {
    rootApiPath = "/admin_api";
    this.registerRouter(routerGloab, admin_api_dir);
    return routerGloab;
  },

  // 注册路由
  registerRouter(routerGloab, dir) {
    let folderPath = __dirname + "/" + dir;
    let controllerFiles = fs.readdirSync(folderPath).filter((f) => {
      return f.endsWith(".js");
    });
    controllerFiles.forEach((f) => {
      let controllerName = require(folderPath + "/" + f);
      console.warn(`${f}`);
      this.fileRouter(routerGloab, controllerName);
    });
  },
  // 注册 路由至 routerGloab
  fileRouter(routerGloab, controller) {
    try {
      for (let url in controller) {
        let path = "";
        if (url.startsWith("GET ")) {
          path = rootApiPath + url.substring(4);
          routerGloab.get(path, controller[url]);
        } else if (url.startsWith("POST ")) {
          path = rootApiPath + url.substring(5);
          routerGloab.post(path, controller[url]);
        } else {
          console.warn("无效路由：" + url);
        }

        console.log(path);
      }
      console.log("\n");
    } catch (e) {
      console.warn(e);
    }
  },
};

module.exports = () => {
  let routerGloab = require("koa-router")();
  baseController.init_admin(routerGloab);
  baseController.init(routerGloab);

  return routerGloab.routes();
};
